<template>
	<div class="home">
		<el-container>
			<!-- 菜单导航 -->
			<el-aside width="auto">
				<Menu />
			</el-aside>
			<el-container>
				<!-- 头部 -->
				<el-header>
					<div class="menu-text">
						<span @click="isOpenMenu">
							<i class="el-icon-s-grid"></i>
						</span>
						<span></span>
					</div>
					<div class="avatar">
						<el-avatar>
							<img src="@/assets/img/icon/user.jpg" alt="" />
						</el-avatar>
						<span :class="isExit ? 'el-icon-caret-top' : 'el-icon-caret-bottom'" class="arrow" @click="exitMenu"></span>
						<ul class="exit" v-show="isExit">
							<li @click="toastUpdatePwdModal">修改密码</li>
							<li @click="exitSystem">退出登录</li>
						</ul>
					</div>
				</el-header>
				<div class="line"></div>
				<div class="tag-box">
					<Tag />
				</div>
				<el-main :class="$route.name === 'flowDetail' ? 'newFlow' : ''">
					<div class="router-page">
						<transition name="fade-transform">
							<keep-alive :min="1" :max="10" :include="cacheView">
								<router-view> </router-view>
								<router-view> </router-view>
							</keep-alive>
						</transition>
					</div>
				</el-main>
			</el-container>
		</el-container>
		<el-dialog title="修改密码" :visible.sync="showChangePwd" :closeOnClickModal="false">
			<el-form :model="userInfo" status-icon :rules="pwdRules" ref="pwdForm" label-width="100px">
				<el-form-item label="新密码" prop="pass">
					<el-input type="password" v-model="userInfo.pass" autocomplete="off" show-password></el-input>
				</el-form-item>
				<el-form-item label="确认新密码" prop="checkPass">
					<el-input type="password" v-model="userInfo.checkPass" autocomplete="off" show-password></el-input>
				</el-form-item>
			</el-form>
			<div class="btns">
				<el-button @click="showChangePwd = false">取消</el-button>
				<el-button @click="updatePassword" type="primary">确认</el-button>
			</div>
		</el-dialog>
		<el-dialog title="温馨提示" :visible.sync="promptChangePwd" :closeOnClickModal="false">
			<div>您当前使用的登录密码还有{{ expireDays }}天到期，请及时更新登录密码</div>
			<div class="btns">
				<el-button @click="promptChangePwd = false">我知道了</el-button>
				<el-button @click="toastUpdatePwdModal()" type="primary">修改密码</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import { mapState, mapMutations } from 'vuex';
import Menu from './Menu/Menu.vue';
import Tag from './Tag/Tag.vue';
import { logout, getConfigList, updateAccountInfo } from '../api/api';
import { setOperationLogFuntion, addScreenWatermark } from '@/utils/tool.js';
import moment from 'moment';
export default {
	name: 'home',
	components: {
		Menu,
		Tag
	},
	data() {
		const validatePassChecked = (rule, value, callback) => {
			const chineseRegex = /[\u4e00-\u9fff]/;
			if (chineseRegex.test(value)) {
				callback(new Error('格式错误，用户名只能是英文、数字以及 - @ ~ _ 等特殊字符'));
				return;
			}
			if (!value || value.length < 8) {
				callback(new Error('密码强度不足，密码长度至少8个字符，且必须包含大、小写字母、数字、特殊字符'));
			} else if (value !== this.userInfo.pass) {
				callback(new Error('两次输入密码不一致!'));
			} else {
				const uppercaseRegex = /[A-Z]/;
				const lowercaseRegex = /[a-z]/;
				const specialCharRegex = /[!@#$%^&*_\-+={}\[\]\\|;:"'<>,.\/?]/;
				const digitRegex = /[0-9]/;
				let matchNum = 0;
				if (uppercaseRegex.test(value)) matchNum++;
				if (lowercaseRegex.test(value)) matchNum++;
				if (specialCharRegex.test(value)) matchNum++;
				if (digitRegex.test(value)) matchNum++;
				if (matchNum < 4) {
					callback(new Error('密码强度不足，密码长度至少8个字符，且必须包含大、小写字母、数字、特殊字符'));
				} else {
					callback();
				}
			}
		};

		const validatePass = (rule, value, callback) => {
			const chineseRegex = /[\u4e00-\u9fff]/;
			if (chineseRegex.test(value)) {
				callback(new Error('格式错误，用户名只能是英文、数字以及 - @ ~ _ 等特殊字符'));
				return;
			}
			if (!value || value.length < 8) {
				callback(new Error('密码强度不足，密码长度至少8个字符，且必须包含大、小写字母、数字、特殊字符'));
			} else {
				const uppercaseRegex = /[A-Z]/;
				const lowercaseRegex = /[a-z]/;
				const specialCharRegex = /[!@#$%^&*_\-+={}\[\]\\|;:"'<>,.\/?]/;
				const digitRegex = /[0-9]/;
				let matchNum = 0;
				if (uppercaseRegex.test(value)) matchNum++;
				if (lowercaseRegex.test(value)) matchNum++;
				if (specialCharRegex.test(value)) matchNum++;
				if (digitRegex.test(value)) matchNum++;
				if (matchNum < 4) {
					callback(new Error('密码强度不足，密码长度至少8个字符，且必须包含大、小写字母、数字、特殊字符'));
				} else {
					callback();
				}
			}
		};
		return {
			// 标签页
			isExit: false,
			isCollapse: false,
			showChangePwd: false,
			promptChangePwd: false, // 提示修改密码
			expireDays: 1,
			userInfo: {
				userId: '',
				pass: '',
				checkPass: ''
			},
			pwdRules: {
				pass: [
					{ required: true, message: '请输入用户密码', trigger: ['blur', 'change'] },
					{ validator: validatePass, trigger: ['blur', 'change'] }
				],
				checkPass: [
					{ required: true, message: '请输入用户密码', trigger: ['blur', 'change'] },
					{ validator: validatePassChecked, trigger: ['blur', 'change'] }
				]
			},
			pwdUpdateDeadline: ''
		};
	},
	watch: {},
	computed: {
		...mapState({
			cacheView: state => state.menu.cacheView,
			isEditAiFlow: state => state.menu.isEditAiFlow,
			tagList: state => state.menu.tagList,
			// pwdUpdateDeadline: state => state.login.userInfo.pwdUpdateDeadline
		})
	},
	mounted() {
		// 区分不同用户
		this.pwdUpdateDeadline = localStorage.getItem(`zco_admin_pwdUpdateDeadlinee_${window.uid}`) || '';
		console.log(this.cacheView);
		window.addEventListener('storage', () => {
			if (!localStorage.getItem(`zco_admin_token_${window.uid}`)) {
				this.$router.push({ name: 'login', params: { key: 'quit' } });
			}
		});
		this.getConfigList();
		if (this.pwdUpdateDeadline) {
			this.getExpiredDays();
		}
	},
	methods: {
		...mapMutations('login', ['SET_LOGIN_USER_INFO', 'SET_LOGIN_URLS']),
		...mapMutations('menu', ['SET_COLLAPSE', 'SET_CACHE_VIEW']),
		...mapMutations('menu', ['REPLACE_TAG_LIST']),
		exitMenu() {
			this.isExit = !this.isExit;
		},

		getExpiredDays() {
			if (localStorage.getItem(`zco_admin_updatePasswordPrompt_${window.uid}`) === 'Y') {
				return;
			}
			// 目标时间
			const targetTime = this.pwdUpdateDeadline;
			// 当前时间
			const currentTime = moment();
			// 目标时间的moment对象（确保是UTC时间）
			const targetMoment = this.$moment.utc(targetTime);
			// 计算两个时间之间的天数差异
			const daysDifference = targetMoment.diff(currentTime, 'days');
			console.log('pwd expireDays', daysDifference);
			if (daysDifference <= 14) {
				this.promptChangePwd = true;
				this.expireDays = daysDifference;
				localStorage.setItem(`zco_admin_updatePasswordPrompt_${window.uid}`, 'Y');
			}
		},
		async exitSystem() {
			if (!localStorage.getItem(`zco_admin_token_${window.uid}`)) {
				this.$router.push({ name: 'login', params: { key: 'quit' } });
				return;
			}
			await setOperationLogFuntion({ type: '0', category: 'logInOrOut', content: '登出' });
			await this.logout();
			this.$store.commit('SET_LOGIN_USER_INFO', {});
			this.$store.commit('SET_LOGIN_URLS', {});
			localStorage.setItem('token', '');
			localStorage.setItem(`zco_admin_token_${window.uid}`, '');
			localStorage.setItem(`zco_route_permission_${window.uid}`, '');
			localStorage.setItem(`zco_admin_pwdUpdateDeadlinee_${window.uid}`, '');
			localStorage.setItem(`zco_admin_updatePasswordPrompt_${window.uid}`, '');
			this.$router.push({ name: 'login', params: { key: 'quit' } });
		},

		toastUpdatePwdModal() {
			this.showChangePwd = true;
			this.promptChangePwd = false;
		},
		updatePassword() {
			this.$refs['pwdForm'].validate(valid => {
				if (valid) {
					const params = [
						{ op: 'replace', path: '/pwd', value: this.userInfo.pass } // 设置该用户是否失效   Y/失效  N/没有失效
					];
					const data = {};
					data.params = params;
					let userId = localStorage.getItem(`zco_admin_userId_${window.uid}`);
					data.userId = userId;
					this.$Spin.show();
					updateAccountInfo(data)
						.then(() => {
							this.$Spin.hide();
							this.$message.success('修改密码成功！');
							this.showChangePwd = false;
							this.$refs.pwdForm.resetFields();
							// todo 判断一下，如果是第一次，还需要去重新登录？
						})
						.catch(err => {
							this.$Spin.hide();
							this.$requestApiError(err, () => {
								this.$router.push('/');
							});
						});
				}
			});
		},

		isOpenMenu() {
			this.isCollapse = !this.isCollapse;
			this.$store.commit('SET_COLLAPSE', this.isCollapse);
		},
		removeTab() {},
		async logout() {
			try {
				this.removeSubTag();
				await logout();
			} catch (error) {
				console.error('logout error ', error);
			}
		},
		// remove sub page tag
		removeSubTag() {
			try {
				// 去除这3类页面 home form sceneInfo /index/(scene/sceneInfo/[0-9]+|home|form/[0-9]+)
				const list = this.tagList.filter(item => !/\/index\/(scene\/sceneInfo\/[0-9]+|home|form\/[0-9]+)/g.test(item.meta.toPath));

				this.$store.commit('REPLACE_TAG_LIST', list);
			} catch (error) {
				console.error(error);
			}
		},
		async getConfigList() {
			try {
				let data = await getConfigList();
				// itemKey: 'screenWatermark'
				const item = data.data.list.find(item => item.itemKey === 'screenWatermark');
				if (item?.status) {
					addScreenWatermark(item.itemData.param);
				}
			} catch (error) {
				console.log(error);
			}
		}
	}
};
</script>

<style lang="less">
.home {
	.el-submenu__title {
		display: flex;
		align-items: center;
		background-color: #363e4f !important;
	}

	.el-submenu__title:hover {
		background-color: #2b323f !important;
	}

	.el-submenu__icon-arrow {
		opacity: 0;
	}

	.el-menu-box:not(.el-menu--collapse) {
		width: 220px;
		min-height: 400px;
	}
}
</style>
<style lang="less" scoped>
.home {
	width: 100%;
	height: 100%;
	overflow: hidden;
	.btns {
		text-align: right;
	}

	.el-container {
		width: 100%;
		height: 100%;
		background-color: #fff;
	}

	.line {
		border: 1px solid #eee;
	}

	.el-main {
		box-shadow: 0 4px 28px 0 rgba(0, 0, 0, 0.1);
		padding: 0;
		padding: 10px;
		margin: 10px;
	}

	.newFlow {
		// overflow-y: hidden;
		padding: 0;
		margin: 0;
		background-color: #f7f8fb;
	}

	.el-aside {
		background-color: #363e4f;
		overflow: hidden;

		.logo {
			color: #fff;
			padding: 20px 0;
			display: flex;
			align-items: center;
			justify-content: space-around;

			img {
				width: 52px;
				height: 20px;
			}
		}

		.el-menu-box {
			border-right: 0px;
		}

		.logo-img {
			width: 60px;
			height: 20px;
			background: url('@/assets/img/icon/zlogo.png') no-repeat;
		}
	}

	.el-header {
		position: relative;
		display: flex;
		align-items: center;
		justify-content: space-between;

		.menu-text {
			display: flex;
			align-items: center;
			color: #97a8be;

			.el-icon-s-grid {
				padding-right: 10px;
				cursor: pointer;
				font-size: 30px;
			}
		}

		.avatar {
			display: flex;
			align-items: center;

			span {
				cursor: pointer;
				font-size: 24px;
				color: #97a8be;
			}

			.arrow {
				padding-left: 10px;
			}

			.exit {
				position: absolute;
				border: 1px solid #e8eaec;
				z-index: 10;
				background-color: #fff;
				box-shadow: 0 1px 6px rgba(0, 0, 0, 0.1);
				border-right: 4px;
				top: 60px;
				right: -10px;

				li {
					cursor: pointer;
					color: #97a8be;
					font-size: 14px;
					padding: 10px;
				}

				li:hover {
					background-color: #ccc;
				}
			}
		}
	}

	.router-page {
		height: 100%;
	}
}
</style>
